<template>
  <c-back-wrap :loading="loading" go-page="市场管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新增'">
    <QupFormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item prop="marketCode" label="市场编码">
          <el-input v-model="formData.marketCode" placeholder="系统自动生成" disabled />
        </el-form-item>
        <el-form-item prop="marketName" label="市场名称">
          <el-input v-model.trim="formData.marketName" placeholder="市场名称" clearable />
        </el-form-item>
        <!-- 招商入口新增的市场，默认空白市场 -->
        <el-form-item prop="marketType" label="市场类型">
          <!-- <c-dict-select v-if="isEdit" v-model="formData.marketType" dict-type-code="TOBE_MARKET_TYPE" clearable placeholder="市场类型" style="width:100%" /> -->
          <c-dict-range-view :value="formData.marketType" dict-type-code="TOBE_MARKET_TYPE" />
        </el-form-item>
        <el-form-item prop="provinceCode" label="省">
          <c-common-search-province
            :id.sync="formData.provinceId"
            v-model="formData.provinceCode"
            :label.sync="formData.provinceName"
            @update:cityLevel="v=>handleCityLevel(v,'province')"
          />
        </el-form-item>
        <el-form-item prop="cityCode" label="地市">
          <c-common-search-not-province
            :id.sync="formData.cityId"
            v-model="formData.cityCode"
            :label.sync="formData.cityName"
            :disabled="!formData.provinceCode"
            :depend-on-observe="formData.provinceCode"
            :start-observe="startObserve"
            :parent-code="formData.provinceCode"
            @update:cityLevel="v=>handleCityLevel(v,'city')"
          />
        </el-form-item>
        <el-form-item prop="districtCode" label="区/县">
          <c-common-search-not-province
            :id.sync="formData.districtId"
            v-model="formData.districtCode"
            :label.sync="formData.districtName"
            :disabled="!formData.cityCode"
            :depend-on-observe="formData.cityCode"
            :start-observe="startObserve"
            :parent-code="formData.cityCode"
            @update:cityLevel="v=>handleCityLevel(v,'district')"
          />
        </el-form-item>
        <el-form-item prop="streetCode" label="街道/乡镇">
          <c-common-search-not-province
            :id.sync="formData.streetId"
            v-model="formData.streetCode"
            :label.sync="formData.streetName"
            :disabled="!formData.districtCode"
            :depend-on-observe="formData.districtCode"
            :start-observe="startObserve"
            :parent-code="formData.districtCode"
            @update:cityLevel="v=>handleCityLevel(v,'street')"
          />
        </el-form-item>
        <el-form-item prop="agencyCode" label="所属办事处">
          <!-- 筛选范围为启用状态的所有办事处 -->
          <c-common-search-office
            v-model="formData.agencyCode"
            :label.sync="formData.agencyName"
          />
        </el-form-item>
        <el-form-item prop="agencyName" label="办事处编码">
          <span>{{ formData.agencyCode }}</span>
        </el-form-item>
        <el-form-item prop="isOldMerchant" label="是否有老商家">
          <c-dict-select v-model="formData.isOldMerchant" dict-type-code="BOOLEANS" clearable placeholder="是否有老商家" style="width:100%" />
        </el-form-item>
        <el-form-item prop="marketNatrue" label="市场属性">
          <c-dict-select v-model="formData.marketNatrue" dict-type-code="MARKET_NATURE" :include="['A','B','C','L']" clearable placeholder="市场属性" style="width:100%" />
        </el-form-item>
        <el-form-item prop="isLegacyProblem" label="是否有遗留问题">
          <c-dict-select v-model="formData.isLegacyProblem" dict-type-code="BOOLEANS" clearable placeholder="是否有遗留问题" style="width:100%" />
        </el-form-item>
        <!-- 是否有遗留问题值为“是”时，展示此字段 -->
        <el-form-item v-if="[1,'1'].includes(formData.isLegacyProblem)" prop="legacyProblemMsg" label="遗留问题说明" :span="24">
          <el-input v-model="formData.legacyProblemMsg" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="遗留问题说明" clearable />
        </el-form-item>
        <el-form-item prop="dataSource" label="数据来源">
          <!-- 市场类型：通过招商团队新增的市场信息，市场类型默认为“空白市场”； -->
          <!-- 数据来源：通过招商管理新增的市场信息，数据来源默认为“招商团队”，且不可编辑； -->
          <!-- <c-dict-select v-if="isEdit" v-model="formData.dataSource" dict-type-code="CTM_MARKET_DATA_FROM" clearable placeholder="数据来源" style="width:100%" /> -->
          <c-dict-range-view :value="formData.dataSource" dict-type-code="CTM_MARKET_DATA_FROM" />
        </el-form-item>
        <el-form-item prop="cityLevel" label="城市级别">
          <c-dict-select v-model="formData.cityLevel" dict-type-code="CITY_LEVEL" clearable placeholder="城市级别" style="width:100%" />
          <!-- <c-dict-range-view :value="formData.cityLevel" dict-type-code="CITY_LEVEL" /> -->
        </el-form-item>
        <!-- 新增界面不显示此字段，仅编辑界面展示 -->
        <el-form-item v-if="isEdit" prop="isAttractInvestment" label="完成招商">
          <el-switch v-model="formData.isAttractInvestment" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
    </QupFormContainer>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">确定</c-button>
    </div>
  </c-back-wrap>
</template>

<script>
import { marketDetail, marketAdd, marketEdit } from '@/api/channelTask2/market'
export default {
  name: 'AddEdit',
  props: {
    id: {
      type: String,
      default: ''
    },
    // 是否是招商团队
    isAttractInvestmentTeam: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      startObserve: false,
      formData: {
        marketCode: '',
        marketName: '',
        marketType: '',
        provinceCode: '',
        provinceId: '',
        provinceName: '',
        cityCode: '',
        cityId: '',
        cityName: '',
        districtCode: '',
        districtId: '',
        districtName: '',
        streetCode: '',
        streetId: '',
        streetName: '',
        cityLevel: '',
        agencyCode: '',
        agencyName: '',
        isOldMerchant: '',
        marketNatrue: '',
        isLegacyProblem: '',
        legacyProblemMsg: '',
        dataSource: '',
        isAttractInvestment: ''
      },

      detail: {},
      loading: false
    }
  },
  computed: {
    formRules() {
      return {
        marketName: [
          { required: true, validator: (r, v, c) => {
            if (!v) {
              c(new Error('请输入市场名称'))
            } else if (/^ +$/.test(v)) {
              c(new Error('市场名称不能是空格'))
            } else {
              c()
            }
          } }
        ],
        provinceCode: [{ required: true, message: '请选择省份', trigger: 'change' }],
        cityCode: [{ required: true, message: '请选择地市', trigger: 'change' }],
        districtCode: [{ required: this.formData.marketType !== 'A', message: '请选择区/县', trigger: 'change' }],
        streetCode: [{ required: this.formData.marketType !== 'A', message: '请选择街道/乡镇', trigger: 'change' }],
        agencyCode: [{ required: true, message: '请选择所属办事处', trigger: 'change' }],
        isOldMerchant: [{ required: false, message: '请选择是否有老商家', trigger: 'change' }],
        isLegacyProblem: [{ required: false, message: '请选择是否有遗留问题', trigger: 'change' }],
        legacyProblemMsg: [{ required: [1, '1'].includes(this.formData.isLegacyProblem), message: '请输入遗留问题说明', trigger: 'change' }],
        dataSource: [{ required: true, message: '请选择数据来源', trigger: 'change' }],
        marketNatrue: [{ required: true, message: '请选择市场属性', trigger: 'change' }],
        cityLevel: [{ required: true, message: '请选择城市级别', trigger: 'change' }],
        isAttractInvestment: [{ required: true, message: '完成招商', trigger: 'change' }]
      }
    },
    isEdit() {
      return !!this.id
    }
  },
  created() {
    if (!this.isEdit) {
      this.startObserve = true
      if (this.isAttractInvestmentTeam) {
        this.$set(this.formData, 'marketType', 'A')
        this.$set(this.formData, 'dataSource', 'D')
      }
    } else {
      this.syncFormData()
    }
  },
  methods: {
    getDetailData() {
      this.loading = true
      return marketDetail(this.id).then(res => {
        this.loading = false
        this.detail = res.data
      }).catch(() => {
        this.loading = false
      })
    },
    handleCityLevel(cityLevel, type) {
      switch (type) {
        case 'province':
          this.$set(this.formData, 'cityLevel', cityLevel)
          break
        case 'city':
          if (cityLevel === '' && this.formData.provinceCode) {
            return
          }
          this.$set(this.formData, 'cityLevel', cityLevel)
          break
        case 'district':
          if (cityLevel === '' && this.formData.cityCode) {
            return
          }
          this.$set(this.formData, 'cityLevel', cityLevel)
          break
        case 'street':
          if (cityLevel === '' && this.formData.districtCode) {
            return
          }
          this.$set(this.formData, 'cityLevel', cityLevel)
          break

        default:
          break
      }
    },
    detail2FormData() {
      this.startObserve = false
      for (const k of Object.keys(this.formData)) {
        const v = this.detail[k]
        if (v === undefined) {
          continue
        }
        this.$set(this.formData, k, v)
      }
      this.$nextTick(() => {
        this.startObserve = true
      })
    },
    syncFormData() {
      this.getDetailData().then(this.detail2FormData)
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleConfirm() {
      return this.$refs.form.validate().then(() => {
        const data = { ...this.formData }
        data.id = this.id
        if (![1, '1'].includes(data.isLegacyProblem)) {
          data.legacyProblemMsg = ''
        }
        // data.marketName = (data.marketName || '').trim()
        return (this.isEdit ? marketEdit : marketAdd)(data).then(() => {
          this.$message.success('操作成功!')
          this.$pageStack.pop(this.isEdit ? 'onPage' : 'opCondition')
        })
      })
    }
  }
}
</script>
